/** @jsxImportSource @emotion/react */
import * as React from "react";
import {css} from "@emotion/react";
import {
    Text, BlobInputList, InputLine, LineColumn, Table, TableBody, TableRow, Cell,
    TableHead, CCell, RCell, IconCheckSquare, IconSquare, CheckSwitch, TextArea,
} from "customize-easy-ui-component";
import {InspectRecordLayout, InternalItemProps, RepLink,  useItemInputControl, useRepSureButton,} from "../../common/base";
import {useMeasureInpFilter} from "../../common/hooks";
import {Each_ZdSetting,} from "../../hook/useRepTableEditor";
import TableHeaderSlash from "../../common/TableHeaderSlash";


interface Props  extends InternalItemProps{
    label?: string;
    titles?: any[];
}
//[,,]第三个位置：是否有偏低的按钮。   “过量空” “过量空L”两个存储名。
export const items异常指=[ ['烟温高','排烟温度',],['过量空','过量空气系数',true],['炉渣燃','炉渣可燃物含量',],
    ['飞灰燃','飞灰可燃物含量',],['排处一氧','排烟处一氧化碳含量',],['散热失','散热损失',],['漏煤比','漏煤量比例',],['渣物理损','灰渣物理热损失',],
];
const items排烟温=[
    ['尾部无布','锅炉尾部无布置受热面、受热面布置不合理或设备故障。','加装、改造或维修尾部受热面（导热油锅炉尾部可加装余热锅炉和空气预热器）。'],
    ['热面结垢','锅炉受热面结垢严重。','清洗锅炉去除水垢，日常加强锅炉水质监测和排污，改造或加装锅炉水处理设备。'],
    ['积灰结焦','锅炉受热面积灰和结焦严重。','进行受热面清灰和清焦，控制炉膛温度防止结焦现象，受热面加装吹灰装置。'],
    ['超负荷','锅炉超负荷运行。','降低锅炉负荷，按额定负荷运行。'],
    ['烟气短路','锅炉内部炉墙损坏造成烟气短路。','停炉检修锅炉，加强锅炉日常维护检修。'],
    ['布置不够','锅炉设计、制造问题：本体受热面布置不够，尾部无布置受热面或受热面布置太小。','提高锅炉制造厂设计制造水平，加强节能审查力度，加装或改造尾部受热面。'],
];
const items空气系=[
    ['鼓风机选','锅炉设备设计、制造及安装的问题：鼓引风机选型不合理、风室密封不好，炉排侧密封不好，以及锅炉风烟系统密封有问题造成漏风。', '维修改造锅炉设备，解决漏风问题。锅炉制造安装单位加强锅炉设计、制造和安装质量。'],
    ['燃烧调整','日常运行中燃烧调整方面的问题。由于工业锅炉运行负荷波动大、煤种变化大，而大多数锅炉燃烧调整主要靠人工，因此无法及时准确地进行燃烧调整，造成鼓风或引风过大。燃油（气）锅炉炉内供风过多。',
        '加强日常锅炉运行管理，及时根据负荷调整燃烧，同时可加装风机变频装置，实现锅炉燃烧自动调整。根据煤种特点锅炉可加装二次风以强化炉内气流的扰动和混合。定期调整燃油（气）锅炉燃烧机供风量。'],
    ['破损漏风','锅炉设备维护不当，锅炉燃烧设备及烟风道破损造成漏风。','维修更换损坏的锅炉设备，解决漏风问题。加强锅炉设备日常维护。'],
    ['操作水平','司炉工操作水平较差，盲目或凭经验进行操作造成过量空气系数过高。','加强司炉工培训和管理，锅炉加装空气系数监测仪表作为操作调整的科学依据。'],
];
const items灰可燃=[
    ['料颗粒度','燃料颗粒度大小和分布不合理，燃料含水率过高或过低。','控制燃料颗粒度大小和含水率，加装分层给煤装置。'],
    ['炉排漏煤','炉排制造或设计不合理，漏煤严重。','改造维修炉排，减少漏煤。'],
    ['风煤配比','日常运行操作问题：煤层厚度过大和进煤速度过快，风煤配比不合理，过量空气系数太小。','根据燃烧状况合理调整煤层厚度和进煤速度，合理选择风煤比，适当加大过量空气系数。'],
    ['设计煤种','实际使用煤种与设计煤种不同，炉膛结构和炉拱无法适应煤种燃烧。','改造炉膛结构和炉拱，敷设卫燃带以适应实际使用煤种燃烧。'],
    ['膛温过低','炉膛温度过低。','提高炉膛温度，加装空气预热器提高助燃空气温度，强化炉膛燃烧。'],
];
const items一氧化=[
    ['燃油雾化','燃油（气）锅炉燃烧调整不正常，油（气）量和风量匹配不合理或混合不均匀，燃油雾化不良。','合理调整锅炉燃烧，根据油（气）量合理选择配风量，更换或清洗油嘴。'],
    ['炉膛结烧','锅炉炉膛结构不合理及布置方式局限性，燃烧不完全。','改造炉膛结构、加装二次风，改善炉膛燃烧状况。'],
    ['搅拌燃料','锅炉在进料过程中，炉内燃料堆积得不到搅拌，燃料在缺氧状态下燃烧产生大量的一氧化碳。','通过在锅炉前端加装预燃烧器，使燃料预燃烧后送至炉体内进行二次燃烧的控制措施。'],
];
const items散热损=[
    ['保温效果','锅炉设备设计、制造及安装的问题造成锅炉保温效果较差，散热损失过大。','维修改造或增加锅炉本体、烟风道及管道保温层。锅炉制造安装单位加强锅炉设计、制造和安装质量。'],
    ['维保不当','日常运行维护保养不当使锅炉本体、炉墙、烟风道及管道保温层损坏。供热、排污系统中阀门、法兰、垫片损坏或关闭不紧造成跑、滴、漏现象。',
        '加强锅炉维护保养，整修锅炉本体、炉墙、烟风道及管道保温层，防止和减少热量损失。消除供热、排污系统中阀门和接头部位的跑、滴、漏现象。在锅炉辐射保温层内喷涂高温远红外涂料，提高炉膛吸热能力，减少热量损失。'],
];
export const entry原因分=[ ['排烟温度偏高', items排烟温],['过量空气系数偏高',items空气系],['炉渣飞灰可燃物含量偏高',items灰可燃],
             ['一氧化碳含量偏高',items一氧化],['散热损失偏大',items散热损] ];


export const itemA异常指: string[]=['小综述' ];
items异常指.forEach(([name,_,twozb], i:number)=>{
    itemA异常指.push(name as string);
    if(twozb)   itemA异常指.push(name+'L');
});
export const SituationSuggest=
    React.forwardRef(({ children, show ,alone=true,refWidth,verId,redId,nestMd,label,rep}:Props,  ref
    ) => {
        const [getInpFilter]=useMeasureInpFilter(null,itemA异常指, );
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const sureButton=useRepSureButton({inp, ref, nestMd, redId});
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                                 alone={alone}  label={label!}>
                <Text variant="h5">{label}:</Text>
                <hr/>
                <LineColumn >
                    {(new Array(items异常指.length)).fill(null).map((_, w: number) => {
                        const cfg=items异常指[w];
                        const name=cfg[0] as string;
                        return <React.Fragment key={w}>
                            <InputLine key={w} label={`${cfg[1]}-偏高:`}>
                                <CheckSwitch  checked={inp?.[name] || false} onChange={e => {
                                    if(cfg[2] && !inp?.[name] && inp?.[name+'L'])   setInp({...inp, [name+'L']: undefined, [name]: inp?.[name] ? undefined : true});
                                    else setInp({...inp, [name]: inp?.[name] ? undefined : true})
                                    }} />
                            </InputLine>
                            {cfg[2] && <InputLine key={w+'L'} label={`${cfg[1]}-偏低:`}>
                                <CheckSwitch  checked={inp?.[name+'L'] || false} onChange={e => {
                                    if(inp?.[name] && !inp?.[name+'L'])   setInp({...inp, [name]: undefined, [name+'L']: inp?.[name+'L']? undefined:true});
                                    else setInp({...inp, [name+'L']: inp?.[name+'L']? undefined:true})
                                } }/>
                            </InputLine>
                            }
                        </React.Fragment>;
                        // return <DynamicItems key={w} baseSeq={w+0} inp={inp} setInp={setInp} rep={rep} sureButton={sureButton}/>;
                    })}
                </LineColumn>
                <hr/>异常指标原因分析之上面的&gt;<br/>
                综述：
                <TextArea value={inp?.小综述 || ''} rows={4}
                          onChange={e => setInp({...inp, 小综述: e.currentTarget.value || undefined})}/>
                {children}
                { children }
            </InspectRecordLayout>
        );
    } );

export const itemA原因分: string[]=[ ];
entry原因分.forEach(([_,config] :any[], i:number)=>{
    config.forEach(([name, _,_m] :any, i:number)=>{
        itemA原因分.push(name as string);
    });
});
//分离 下半部分的  原因分析
export const CauseAnalysis=
    React.forwardRef(({ children, show ,alone=true,refWidth,verId,redId,nestMd,label,rep}:Props,  ref
    ) => {
        const [getInpFilter]=useMeasureInpFilter(null,itemA原因分, );
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const sureButton=useRepSureButton({inp, ref, nestMd, redId});
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                                 alone={alone}  label={label!}>
                <Text variant="h5">{label}:</Text>
                <hr/>
                {(new Array(entry原因分.length)).fill(null).map((_, w: number) => {
                    return <DynamicItems key={w} typeIdx={w} inp={inp} setInp={setInp} sureButton={sureButton}/>;
                })}
                { children }
            </InspectRecordLayout>
        );
    } );

const DynamicItems= ( { inp,  setInp, typeIdx, sureButton,} :
                          { inp: any,setInp: React.Dispatch<React.SetStateAction<any>>,typeIdx:number,sureButton:React.ReactNode}
) => {
    const config=entry原因分[typeIdx][1];
    return <div>
            <Text variant="h5">{entry原因分[typeIdx][0]}, 原因分析:</Text>
            <LineColumn >
                {(new Array(config.length)).fill(null).map((_, w: number) => {
                    const cfg=config[w];
                    const name=cfg[0] as string;
                            //<InputLine  key={w} label={cfg[1]}  lineStyle={css`max-width:unset;`}>
                    return <React.Fragment key={w}>
                        <InputLine  key={w} label={`${w+1}：`+cfg[1]}  lineStyle={css({
                            "& .Switch": {
                                flex: 'unset',
                                // padding: '0.675rem 0.578rem'
                            }
                        })}>
                            <CheckSwitch  checked={inp?.[name] || false} onChange={e => {
                                setInp({...inp, [name]: inp?.[name] ? undefined : true})
                            }} />
                        </InputLine>
                    </React.Fragment>;
                })}
        </LineColumn>
       {/*{sureButton}*/}
    </div>;
};

export const itemA它问题: string[] = ['节监测仪','节监测因','它问题因','它问题建','综述' ];
export const OtherProblems =
    React.forwardRef((
        {children, show, alone = true, refWidth, label,}: Props, ref
    ) => {
        const {inp, setInp} = useItemInputControl({ref});
        const [getInpFilter] = useMeasureInpFilter(null, itemA它问题,);
        return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={label!}>
                <Text variant="h5">{label}：</Text>
                <LineColumn>
                    <InputLine  label='锅炉节能监测仪表检查-原因分析'>
                        <BlobInputList value={inp?.节监测因 ?? ''} rows={4} datalist={[]}
                                       onListChange={v => setInp({...inp, 节监测因: v || undefined}) } />
                    </InputLine>
                    <InputLine label='锅炉节能监测仪表检查-要勾选上?'>
                        <CheckSwitch  checked={inp?.节监测仪 || false} onChange={e => {
                                setInp({...inp, 节监测仪: inp?.节监测仪 ? undefined : true})
                        }} />
                    </InputLine>
                    <InputLine  label='其它问题-原因分析' >
                        <BlobInputList value={inp?.它问题因 ?? ''} rows={4}
                                       onListChange={v => setInp({...inp, 它问题因: v || undefined}) } />
                    </InputLine>
                    <InputLine  label='其它问题-建议处理和改进方法' >
                        <BlobInputList value={inp?.它问题建 ?? ''} rows={4}
                                       onListChange={v => setInp({...inp, 它问题建: v || undefined}) } />
                    </InputLine>
                </LineColumn>
                <hr/>
                综述：
                <TextArea value={inp?.综述 || ''} rows={8}
                          onChange={e => setInp({...inp, 综述: e.currentTarget.value || undefined})}/>
                {children}
            </InspectRecordLayout>
        );
});


//异常指标 几行的
const RowsRenxi=Math.ceil(items异常指.length)/2;
//遇到跨页的效果不好：就不用两个行的表头，拆解成两个部分。
export const SituationSuggestVw = ({orc, rep, children}: { orc: any, rep: any, children?: React.ReactNode; }
) => {
    return <>
        <div css={{"@media print": {paddingBottom: '3.5rem', pageBreakInside: 'avoid'}}}>
            <Text id='SituationSuggest' variant="h2" css={{
                textAlign: 'center', marginTop: '1rem',
            }}>五、测试情况分析和建议表</Text>
            <div css={{display: 'flex', justifyContent: 'space-between'}}>
                <Text>测试日期：{orc?.检验日期}</Text>
                <Text>报告编号：{rep.isp.no}</Text>
            </div>
        </div>
        <Table fixed={ ["9%", "20%", "24%", "9%","%"] }  tight miniw={800} css={{borderCollapse: 'collapse', "@media print": {marginTop: '-3.5rem'}}}>
            <TableBody>
                <RepLink rep={rep} tag={'SituationSuggest'}>
                    <TableRow>
                        <CCell>锅炉型号</CCell><CCell colSpan={2}>{orc?.型号}</CCell>
                        <CCell>产品编号</CCell><CCell>{orc?.出厂编号}</CCell>
                    </TableRow>
                    <TableRow>
                        <CCell>委托单位</CCell><CCell colSpan={2}>{orc?.服务单位}</CCell>
                        <CCell>使用单位</CCell><CCell>{orc?.使用单位}</CCell>
                    </TableRow>
                    <TableRow>
                        <Cell colSpan={2}>
                            <div css={{display: 'flex',justifyContent:'center'}}>
                                <Text>锅炉效率η：</Text>
                                <Text>{orc?.简效率?.m??'／'}%</Text>
                            </div>
                        </Cell>
                        <Cell colSpan={3}>
                            <div css={{display: 'flex',justifyContent:'space-evenly'}}>
                                <Text>q2:{orc?.烟热损?.m??'／'}</Text>
                                <Text>q3:{orc?.气未全燃?.m??'／'}</Text>
                                <Text>q4:{orc?.固未全燃?.m??'／'}</Text>
                                <Text>q5:{orc?.散热损?.m??'／'}</Text>
                                <Text>q6:{orc?.物理热损?.m??'／'}</Text>
                            </div>
                        </Cell>
                    </TableRow>
                    <TableRow>
                        <Cell colSpan={5}>
                            <div css={{display: 'flex'}}>
                                <Text>综述：</Text>
                                <Text css={{ whiteSpace: 'pre-wrap'}}>{orc?.小综述 || '／'}</Text>
                            </div>
                        </Cell>
                    </TableRow>
                </RepLink>
            </TableBody>
        </Table>
        <Table fixed={ ["9%", "28%", "17%", "28%","%"]} css={{borderCollapse: 'collapse', }} tight miniw={800}>
            <TableBody>
              <RepLink rep={rep} tag={'SituationSuggest'}>
                { (new Array(RowsRenxi)).fill(null).map((_, w: number) => {
                    const cfg1=items异常指[w*2];
                    const cfg2=items异常指[w*2+1];
                    return <TableRow key={w}>
                        {w===0 && <CCell rowSpan={RowsRenxi}>能效测试异常指标</CCell>}
                        <RCell>{cfg1[1]}</RCell>
                        <Cell><div css={{display: 'flex',alignItems: 'center'}}>{orc?.[cfg1[0] as string]? <IconCheckSquare size='sm'/> : <IconSquare size='sm'/>}&nbsp;偏高</div>
                        </Cell>
                        <RCell>{cfg2[1]}</RCell>
                        <Cell>
                            {cfg2[2] ? <div css={{display: 'flex', justifyContent: 'space-between'}}>
                                        <div css={{display: 'flex', alignItems: 'center'}}>{orc?.[cfg2[0] as string] ?
                                            <IconCheckSquare size='sm'/> : <IconSquare size='sm'/>}&nbsp;偏高
                                        </div>
                                        <div css={{display: 'flex', alignItems: 'center'}}>{orc?.[(cfg2[0] as string)+'L'] ?
                                            <IconCheckSquare size='sm'/> : <IconSquare size='sm'/>}&nbsp;偏低
                                        </div>
                                </div>
                                :
                                <div css={{display: 'flex', alignItems: 'center'}}>{orc?.[cfg2[0] as string] ?
                                    <IconCheckSquare size='sm'/> : <IconSquare size='sm'/>}&nbsp;偏高</div>
                            }
                        </Cell>
                    </TableRow>;
                })}
              </RepLink>
            </TableBody>
        </Table>
        <Table fixed={ ["9%", "28%", "17%", "28%","%"]} css={{borderCollapse: 'collapse', }} tight miniw={800}>
            <TableHead>
                <TableRow>
                    <TableHeaderSlash/>
                    <CCell colSpan={2}>原因分析</CCell><CCell colSpan={2}>建议处理和改进方法</CCell>
                </TableRow>
            </TableHead>
            <TableBody>
                { (new Array(entry原因分.length)).fill(null).map((_, w: number) => {
                    return <DynamicItemsVw key={w} typeIdx={w} rep={rep} orc={orc}/>;
                })}
               <RepLink rep={rep} tag={'OtherProblems'}>
                <TableRow>
                   <CCell>锅炉节能监测仪表检查</CCell>
                    <Cell colSpan={2}>
                        <div css={{display: 'flex', alignItems: 'center'}}>
                            <div>
                                {orc?.节监测仪 ? <IconCheckSquare size='sm'/> : <IconSquare size='sm'/>}
                            </div>
                            {orc?.节监测因}
                        </div>
                    </Cell>
                    <CCell colSpan={2}>建议配置相关监测仪表并记录监测数据。</CCell>
                </TableRow>
                <TableRow>
                    <CCell>其它问题</CCell>
                    <CCell colSpan={2}>
                        {orc?.它问题因 ??'／'}
                    </CCell>
                    <CCell colSpan={2}>{orc?.它问题建 ??'／'}</CCell>
                </TableRow>
                <TableRow>
                    <Cell colSpan={5}><div css={{minHeight: '2rem', whiteSpace: 'pre-wrap'}}>
                        综述：<br/>
                        {orc?.综述 || '／'}
                    </div></Cell>
                </TableRow>
              </RepLink>
           </TableBody>
         </Table>
        {children}
    </>;
};

const DynamicItemsVw= ( { orc, typeIdx,rep} : { orc: any,typeIdx:number,rep:any}
) => {
    const config=entry原因分[typeIdx][1] as [];
                    //key报错  Object.assign( DomNode,    { key: 'W'+insertIdx });         key={typeIdx}
    return (<>
            <RepLink rep={rep} tag={'CauseAnalysis'}>
                {config.map(([name, cause, meth] :string[], i: number) => {
                    return <TableRow  key={i}>
                        {i===0 && <CCell rowSpan={config.length}>{entry原因分[typeIdx][0]}</CCell>}
                        <Cell colSpan={2}>
                            <div css={{display: 'flex', alignItems: 'center'}}>
                                <div>
                                    {orc?.[name] ? <IconCheckSquare size='sm'/> : <IconSquare size='sm'/>}
                                </div>
                                {cause}
                            </div>
                        </Cell>
                        <CCell colSpan={2}>{meth}</CCell>
                    </TableRow>;
                })}
          </RepLink>
        </>
    );
};
